package com.egao.common.manage.school;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.egao.common.core.annotation.ApiPageParam;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.counsel.CounselConstants;
import com.egao.common.module.counsel.entity.Counsel;
import com.egao.common.module.counsel.entity.CounselStudent;
import com.egao.common.module.counsel.entity.CounselStudentFeedback;
import com.egao.common.module.counsel.entity.CounselTeacher;
import com.egao.common.module.counsel.enums.CounselTypeEnum;
import com.egao.common.module.counsel.param.CounselParam;
import com.egao.common.module.counsel.param.CounselStudentParam;
import com.egao.common.module.counsel.result.CounselCalendar;
import com.egao.common.module.counsel.result.CounselCalendarColumns;
import com.egao.common.module.counsel.service.CounselService;
import com.egao.common.module.counsel.service.CounselStudentFeedbackService;
import com.egao.common.module.counsel.service.CounselStudentService;
import com.egao.common.module.counsel.service.CounselTeacherService;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * @author lym
 * @date 2022/2/11 13:58
 */
@Api(tags = "预约咨询管理")
@RestController
@RequestMapping("${api}")
public class SchoolCounselController extends BaseController {

    @Autowired
    private CounselService counselService;
    @Autowired
    private CounselTeacherService counselTeacherService;
    @Autowired
    private CounselStudentService counselStudentService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private CounselStudentFeedbackService counselStudentFeedbackService;

    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @ApiOperation(value = "咨询师信息")
    @GetMapping("/school/counsel/teacher/list")
    public JsonResult teacherList() {
        List<CounselTeacher> list = counselTeacherService.list(null);
        return JsonResult.ok().setData(list);
    }

    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @ApiOperation(value = "咨询师信息")
    @GetMapping("/school/counsel/teacher")
    public JsonResult teacher() {
        CounselTeacher counselTeacher = counselTeacherService.getByUserId(getLoginUserId());
        if (counselTeacher == null) {
            return JsonResult.error("您不是咨询师");
        }
        counselTeacher.setName(getLoginUser().getName());
        return JsonResult.ok().setData(counselTeacher);
    }

    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @ApiOperation(value = "保存咨询周期")
    @PostMapping("/school/counsel/save")
    public JsonResult saveCounsel(@RequestBody CounselParam counselParam) {
        if (counselService.saveCycle(counselParam)) {
            return JsonResult.ok("保存成功");
        }
        return JsonResult.error("保存失败");
    }

    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @ApiOperation(value = "更新咨询师信息")
    @OperLog(value = "预约咨询管理", desc = "更新咨询师信息", result = true)
    @PutMapping("/school/counsel/teacher")
    public JsonResult teacher(@RequestBody CounselTeacher counselTeacher) {
        if (counselTeacherService.updateById(counselTeacher)) {
            return JsonResult.ok("更新成功");
        }

        return JsonResult.error("更新失败");
    }

    @ApiOperation(value = "预约咨询日历")
    @GetMapping("/school/counsel/calendar")
    public JsonResult calendar(String date) {
        List<CounselCalendarColumns> list = counselService.calendar(date, getLoginUser());
        return JsonResult.ok().setData(list);
    }

    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @ApiOperation(value = "更改预约咨询")
    @OperLog(value = "更改预约咨询", desc = "更改预约咨询", result = true)
    @PutMapping("/school/counsel")
    public JsonResult update(@RequestBody Counsel counsel) {
        Counsel c = counselService.getById(counsel.getId());
        if (c.getCount() < counsel.getCount()) {
            counsel.setSurplusCount(c.getSurplusCount() + (counsel.getCount() - c.getCount()));
        }
        if (counselService.updateCounsel(counsel)) {
            return JsonResult.ok();
        }
        return JsonResult.error();
    }

    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @ApiOperation(value = "查询当前是否有人预约")
    @OperLog(value = "查询当前是否有人预约", desc = "查询当前是否有人预约", result = true)
    @PostMapping("/school/counsel/query-student")
    public JsonResult queryStudent(@RequestBody Counsel counsel) {
        CounselStudent counselStudent = counselStudentService.getOne(
                new LambdaQueryWrapper<CounselStudent>().eq(CounselStudent::getCounselId, counsel.getId())
                        .last("limit 1")
        );
        Student student = counselStudent != null
                ?  studentService.getById(counselStudent.getStudentId())
                : null;
        if (Objects.isNull(student)) {
            return JsonResult.error();
        }
        return JsonResult.ok();
    }

    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @ApiOperation(value = "取消预约时间")
    @OperLog(value = "预约咨询管理", desc = "取消预约时间", result = true)
    @PutMapping("/school/counsel/cancel")
    public JsonResult cancel(@RequestBody Counsel counsel) {
        CounselStudent counselStudent = counselStudentService.getOne(
                new LambdaQueryWrapper<CounselStudent>().eq(CounselStudent::getCounselId, counsel.getId())
                .last("limit 1")
        );
        Student student = counselStudent != null
                ?  studentService.getById(counselStudent.getStudentId())
                : null;
        return counselService.cancelCounsel(counsel, student);
    }

    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @ApiOperation(value = "（管理员）学生预约列表")
    @ApiPageParam
    @GetMapping("/school/counsel/student")
    public PageResult<CounselStudent> student(HttpServletRequest request) {
        PageParam<CounselStudent> pageParam = new PageParam<>(request);
        return new PageResult<>(counselStudentService.listPage(pageParam), pageParam.getTotal());
    }


    @PreAuthorize("hasAnyAuthority('school:counsel:manage', 'school:counsel-student:list')")
    @ApiOperation(value = "咨询反馈详情")
    @GetMapping("/school/counsel/feedback/{id}")
    public JsonResult feedback(@PathVariable("id") Integer id) {
        List<CounselStudentFeedback> list = counselStudentFeedbackService.list(
                new LambdaQueryWrapper<CounselStudentFeedback>()
                        .eq(CounselStudentFeedback::getCounselStudentId, id)
                        .orderByDesc(CounselStudentFeedback::getId)
        );

        if (list.size() > 0) {
            return JsonResult.ok().setData(list.get(0));
        }
        return JsonResult.ok();
    }

    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @OperLog(value = "补录导入", desc = "补录导入", result = true)
    @ApiOperation("补录导入")
    @Transactional
    @PostMapping("/school/counsel/import")
    public JsonResult importCounsel(MultipartFile file, Integer id) {
        return counselStudentService.importCounsel(file, id);
    }


    @PreAuthorize("hasAuthority('school:counsel-student:list')")
    @OperLog(value = "查询指定日期开放的预约咨询", desc = "查询指定日期开放的预约咨询", result = true)
    @ApiOperation("查询指定日期开放的预约咨询")
    @Transactional
    @GetMapping("/school/counsel/query")
    public JsonResult save(@Param("date") Date date) {
        LambdaQueryWrapper<Counsel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Counsel::getCounselDate, date)
                .eq(Counsel::getState, CounselConstants.STUDENT_STATE);
        return JsonResult.ok().setData(counselService.list(queryWrapper));
    }

    @PreAuthorize("hasAuthority('school:counsel:manage')")
    @OperLog(value = "更改学生赴约状态", desc = "更改学生赴约状态", result = true)
    @ApiOperation("更改学生赴约状态")
    @Transactional
    @GetMapping("/school/counsel/check-state/{id}")
    public JsonResult checkState(@PathVariable("id") Integer id) {
        LambdaUpdateWrapper<CounselStudent> luw = new LambdaUpdateWrapper<>();
        luw.eq(CounselStudent::getId, id)
                .set(CounselStudent::getState, CounselConstants.STUDENT_STATE_PROMISE);
        if (!counselStudentService.update(luw)) {
            return JsonResult.error("更改赴约状态失败");
        }
        return JsonResult.ok("更改赴约状态成功");
    }





}
